/*
 * Copyright (c) 2025 Oracle and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.helidon.telemetry.otelconfig;

import java.util.function.Supplier;

import io.helidon.config.Config;
import io.helidon.service.registry.Service;

import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.OpenTelemetry;

@Service.Singleton
@Service.RunLevel(Service.RunLevel.STARTUP)
class HelidonOpenTelemetryServiceFactory implements Supplier<OpenTelemetry> {

    private final Config config;

    @Service.Inject
    HelidonOpenTelemetryServiceFactory(Config config) {
        this.config = config;
    }

    @Override
    public OpenTelemetry get() {
        OpenTelemetry result;
        var otelConfig = OpenTelemetryConfig.create(config.get(HelidonOpenTelemetry.CONFIG_KEY));
        try {
            result = HelidonOpenTelemetry.create(otelConfig)
                    .openTelemetry();
        } catch (Exception e) {
            /*
            The configuration set "global" to "true" and so HelidonOpenTelemetry tried to tell OTel to use the
            configured OpenTelemetry instance as the global one. The exception probably is because the OTel global instance
            was already set. In that case, register the current OTel global instance in our registry so code
            that retrieves it from our registry will use the actual OTel global instance.
             */
            result = GlobalOpenTelemetry.get();
        }

        return result;
    }
}
